<!DOCTYPE html>
<html>
<head>
    <title>FLV Video Stream</title>
</head>
<body>
    <h1>FLV Video Stream</h1>

    <!-- 启动视频流按钮 -->
    <button id="startStreamButton" onclick="startVideoStream()">Start Video Stream</button>
    <script src="{{ url_for('static', filename='flv.js') }}"></script>
    <!-- 停止视频流按钮 -->
    <button id="stopStreamButton" onclick="stopVideoStream()" disabled>Stop Video Stream</button>

    <!-- 视频播放器 -->
    <video id="flvPlayer" width="640" height="480" controls></video>

    <script>
        const flvPlayer = document.getElementById('flvPlayer');
        const startButton = document.getElementById('startStreamButton');
        const stopButton = document.getElementById('stopStreamButton');
        let ws = null;

        // 启动视频流按钮点击事件
        function startVideoStream() {
            startButton.disabled = true;
            stopButton.disabled = false;

            // 发起 GET 请求到服务器的start_video_stream接口
            fetch('/start_video_stream', {
                method: 'GET'
            })
            .then(response => {
                if (response.status === 200) {
                    // 使用 WebSocket 连接到服务器
                    console.log('WebSocket start.');
                    const videoElement = document.getElementById('flvPlayer');
                    if (flvjs.isSupported()) {
                        const flvPlayer = flvjs.createPlayer({
                            type: 'flv',
                            isLive: true,
                            url: 'ws://'+this.location.hostname+':2224'
                        });
                        flvPlayer.attachMediaElement(videoElement);
                        flvPlayer.load();
                        flvPlayer.play();
                    }
                }
            });
        }

        // 停止视频流按钮点击事件
        function stopVideoStream() {
            startButton.disabled = false;
            stopButton.disabled = true;
            // 关闭 WebSocket 连接
            if (ws !== null) {
                ws.close();
                ws = null;
            }

            // 发起 GET 请求到服务器的stop_video_stream接口
            fetch('/stop_video_stream', {
                method: 'GET'
            });
        }
    </script>
</body>
</html>

